package com.yuqing.sentimentapp.home.acitivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.linkface.baselibrary.http.BaseApiService;
import com.linkface.baselibrary.http.BaseBean;
import com.linkface.baselibrary.utils.FileUtils;
import com.linkface.baselibrary.utils.LogUtil;
import com.yuqing.sentimentapp.BuildConfig;
import com.yuqing.sentimentapp.base.BaseObserver;
import com.yuqing.sentimentapp.R;
import com.yuqing.sentimentapp.base.BaseActivity;
import com.yuqing.sentimentapp.home.bean.NewsDetailDataBean;
import com.yuqing.sentimentapp.interfaces.DownloadListener;
import com.yuqing.sentimentapp.module.DownloadPdfHelp;
import com.yuqing.sentimentapp.module.ModuleManager;
import com.yuqing.sentimentapp.utils.SharePrefrenceHelper;
import com.yuqing.sentimentapp.utils.net.NetWorkUtil;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by shenhe on 2019/4/25.
 */
public class NewsDetailActivity extends BaseActivity {
    private final static String PDFJS_PREFIX = "file:///android_asset/pdfjs/web/viewer.html?file=";
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.webView)
    WebView mWebView;
    private String webUrl = "";
    private boolean isUrl;
    private String title;
    private boolean isPDF;
    private DownloadPdfHelp downloadPdfHelp;
    private String localPdfPath;

    public static void start(Context context, String url, String title, boolean isUrl) {
        Intent intent = new Intent(context, NewsDetailActivity.class);
        intent.putExtra("webUrl", url);
        intent.putExtra("title", title);
        intent.putExtra("isUrl", isUrl);
        context.startActivity(intent);
    }

    public static void start(Context context, String url, String title, boolean isUrl, boolean isPDF) {
        Intent intent = new Intent(context, NewsDetailActivity.class);
        intent.putExtra("webUrl", url);
        intent.putExtra("title", title);
        intent.putExtra("isUrl", isUrl);
        intent.putExtra("isPDF", isPDF);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_news_detail;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        initIntentData();
        initWebView();
        mTvTitle.setText(title);
        mTvTitle.setMaxEms(10);
        mTvTitle.setSingleLine();
        mTvTitle.setEllipsize(TextUtils.TruncateAt.END);
        if (isUrl) {
            if (isPDF) {
                loadPdf();
            } else {
                mWebView.loadUrl(webUrl);
            }
        } else {
            //此时webUrl是newsId
            loadData();
        }
    }

    private void loadPdf() {
        if (downloadPdfHelp == null) {
            downloadPdfHelp = new DownloadPdfHelp(this);
        }
        downloadPdfHelp.downloadFile(BuildConfig.Base_URL + "/analysisView?id=" + webUrl, webUrl + ".pdf", new DownloadListener() {

            @Override
            public void onStart() {
                startProgressDialog();
            }

            @Override
            public void onProgress(int currentLength) {
//                        LogUtil.d("当前进度：" + currentLength);
            }

            @Override
            public void onFinish(String localPath) {
                localPdfPath = localPath;
                runOnUiThread(() -> {
                    Log.d("DownloadPdfHelp", "file path =  " + localPath);
                    loadLocalPDF(localPath);
                    stopProgressDialog();
                });
            }

            @Override
            public void onFailure(String erroInfo) {

            }
        });
    }

    public void loadLocalPDF(String path) {
        mWebView.loadUrl(PDFJS_PREFIX + "file://" + path);
    }

    public void loadOnlinePDF(String url) {
        mWebView.loadUrl(PDFJS_PREFIX + url);
    }

    private void loadData() {
        ModuleManager.getInstance().getNewsDetailResult(this, SharePrefrenceHelper.getLoginMobile(), webUrl)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new BaseObserver<NewsDetailDataBean>() {
            @Override
            protected void hideDialog() {
                stopProgressDialog();
            }

            @Override
            protected void showDialog() {
                startProgressDialog();
            }

            @Override
            protected void onSuccess(NewsDetailDataBean newsDataBean) {
                if (newsDataBean == null) {
                    return;
                }
                NewsDetailDataBean.DataBean data = newsDataBean.getData();
                if (data == null) {
                    return;
                }
                mTvTitle.setText(data.getTitle());
                mWebView.loadDataWithBaseURL(null, data.getContent(), "text/html", "utf-8", null);
            }

            @Override
            protected void onFailure(String message) {

            }
        });
    }

    private void initIntentData() {
        Intent intent = getIntent();
        if (intent != null) {
            webUrl = intent.getStringExtra("webUrl");
            title = intent.getStringExtra("title");
            isUrl = intent.getBooleanExtra("isUrl", false);
            isPDF = intent.getBooleanExtra("isPDF", false);
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        int scale = dm.densityDpi;
        if (scale == 240) { //设置自动适配
            mWebView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
        } else if (scale == 160) {
            mWebView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        } else {
            mWebView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
        }
//        支持特殊的javascript脚本语句
        mWebView.setWebChromeClient(new WebChromeClient());
        //                支持javascript脚本语句
        //取消滚动条
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        //触摸焦点起作用
        mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);

        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setAllowFileAccessFromFileURLs(true);
        mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);

        if (NetWorkUtil.isConnected(null)) {
            mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);  //设置 缓存模式
        } else {
            mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  //设置 缓存模式
        }
        // 开启 DOM storage API 功能
        mWebView.getSettings().setDomStorageEnabled(true);
        //开启 database storage API 功能
        mWebView.getSettings().setDatabaseEnabled(true);
        //开启 Application Caches 功能
        mWebView.getSettings().setAppCacheEnabled(true);
        //webview屏幕适配
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setUseWideViewPort(true);
        //支持自动加载图片
        mWebView.getSettings().setLoadsImagesAutomatically(true);

        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        //支持缩放
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setDisplayZoomControls(false);//不显示缩放按钮
        mWebView.setWebViewClient(new WebViewClient() {
            //页面加载开始
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            //页面加载完成
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!TextUtils.isEmpty(url)) {
                    view.loadUrl(url);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
        //5.0以上需要开启第三方Cookie存储
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true);
        }
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();
    }

    @OnClick({R.id.iv_back})
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.iv_back:
                goBack();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void goBack() {
        if (mWebView.canGoBack()) {
            mWebView.goBack(); // 后退
        } else {
            finish();
        }
    }

    @Override
    public void onResume() {
        mWebView.onResume();//恢复
        super.onResume();
    }

    @Override
    public void onPause() {
        mWebView.onPause(); //暂停应用内所有WebView //mWebView.onResume(); 恢复。
        super.onPause();
    }

    @Override
    public void onDestroy() {
        FileUtils.deleteSDDir(DownloadPdfHelp.PATH_CHALLENGE_PDF);
        mWebView.destroy();
        super.onDestroy();
    }
}
